from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.tree import DecisionTreeClassifier
from sklearn.metrics import accuracy_score
from matplotlib.colors import ListedColormap
import numpy as np
import matplotlib.pyplot as plt

# 加载数据集
iris = load_iris()
iris_feature = iris.data
iris_target = iris.target

# 划分训练集和测试集
feature_train, feature_test, target_train, target_test = train_test_split(iris_feature, iris_target, test_size=0.33,
                                                                          random_state=42)

# 配置并训练模型
model = DecisionTreeClassifier()
clf = model.fit(feature_train[:, 0:2], target_train)

# 模型预测
# predict_results = clf.predict(feature_test)
#
# # 模型评估
# accuracy = accuracy_score(predict_results, target_test)
# print(f"模型的准确率: {accuracy}")


def plot_decision_region(X, y, classifier, resolution=0.02):
    markers = ('s', 'x', 'o', '^', 'v')
    colors = ('red', 'blue', 'lightgreen', 'gray', 'cyan')
    # 背景色
    cmap = ListedColormap(colors[:len(np.unique(y))])

    # plot the decision surface
    # 这里+1  -1的操作我理解为防止样本落在图的边缘处，不知道对不对
    x1_min, x1_max = X[:, 0].min() - 1, X[:, 0].max() + 1
    # print(x1_min, x1_max)

    x2_min, x2_max = X[:, 1].min() - 1, X[:, 1].max() + 1
    # print(x2_min, x2_max)

    # 生成网格点坐标矩阵
    xx1, xx2 = np.meshgrid(np.arange(x1_min, x1_max, resolution),
                           np.arange(x2_min, x2_max, resolution))
    Z = classifier.predict(np.array([xx1.ravel(), xx2.ravel()]).T)
    Z = Z.reshape(xx1.shape)
    # 绘制轮廓等高线  alpha参数为透明度
    plt.contourf(xx1, xx2, Z, alpha=0.3, cmap=cmap)
    plt.xlim(xx1.min(), xx1.max())
    plt.ylim(xx2.min(), xx2.max())

    # plot class samples
    for idx, cl in enumerate(np.unique(y)):
        plt.scatter(x=X[y == cl, 0],
                    y=X[y == cl, 1],
                    alpha=0.8,
                    c=colors[idx],
                    marker=markers[idx],
                    label=cl,
                    edgecolors='black')


print(feature_train[:, 0:2])
print(target_train)
plot_decision_region(feature_train[:, 0:2], target_train, classifier=clf, resolution=0.01)
plt.xlabel('petal length')
plt.ylabel('petal width')
plt.legend(loc='upper left')
plt.show()
